package com.geeyuu.android.service;

import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.ContentValues;
import android.content.Context;
import android.os.Bundle;
import android.os.Message;

import com.geeyuu.android.GeePrefrence;
import com.geeyuu.android.model.BaseUserInfo;
import com.geeyuu.android.model.ChatInfo;
import com.geeyuu.android.utils.AndroidUtil;
import com.geeyuu.android.utils.CommonUtil;
import com.geeyuu.android.utils.LogUtil;

public class ReceiveMsgHandle {

    /**
     * 处理返回码的各种情况
     * 
     * @return
     */
    private static int handleReturnCode(long returnCode, String jsonStr) {
        if (returnCode == ProtocolCommand.CMD_ERROR_NONE || returnCode == ProtocolCommand.CMD_ACCOUNT) { // 账号不存在客户端认为是正常消息的一种
            LogUtil.i(TAG, "return code 正常 :" + returnCode);
            return ERROR_CODE_OK;
        } else {
            // 应该还需要做更多的处理，代码待补..
            // ...
            LogUtil.i(TAG, "返回消息不正常，错误码:" + returnCode);
            if (null != jsonStr) {
                try {
                    JSONObject jsonObject = new JSONObject(jsonStr);
                    String errorTitle = jsonObject.optString("error_title");
                    String errorContent = jsonObject.optString("error_content");
                    String errorLog = jsonObject.optString("error_log");
                    LogUtil.w(TAG, "===============================");
                    LogUtil.w(TAG, "errorTitle:" + errorTitle);
                    LogUtil.w(TAG, "errorContent:" + errorContent);
                    LogUtil.w(TAG, "errorLog:" + errorLog);
                    LogUtil.w(TAG, "===============================");
                } catch (JSONException e) {
                    LogUtil.e(TAG, "return code = 0 的情况下解析json有异常", e);
                }
            } else {
                LogUtil.e(TAG, "return code 为0，但是json却为null");
            }
            return ERROR_CODE_ERROR;
        }
    }

    private static final String TAG = "ReceiveMsgHandle";
    public static final int ERROR_CODE_OK = 0;
    public static final int ERROR_CODE_ERROR = 1;

    /**
     * 处理发送给界面的消息
     * 
     * @param buffer
     *            为一条完整消息
     * @return
     */
    public static Message handleReveiveMsg(Context context, int cmd, int protocolVersion, long errorCode,
            String jsonStr, RECmd reCmd, ConcurrentHashMap<Integer, RECmd> cmds) {
        
        LogUtil.d(TAG, "服务端返回的json: " + (jsonStr != null ? jsonStr : "null"));
        
        Message msg = new Message();
        // 数据都放在data里面发给界面
        Bundle dataForClient = new Bundle();
        msg.what = cmd;
        msg.setData(dataForClient);
        
        if(null == reCmd && !ProtocolCommand.isPushCommand(cmd)){
            msg.arg1 = ERROR_CODE_ERROR;
            LogUtil.e(TAG, "处理返回的时候，对应的发送cmd为null");
            return msg;
        }
        
        if(reCmd != null){
            msg.obj = reCmd.tag;
        }

        int resultCode = ERROR_CODE_ERROR;
        resultCode = handleReturnCode(errorCode, jsonStr);
        if (resultCode == ERROR_CODE_ERROR) {
            msg.arg1 = ERROR_CODE_ERROR;
            return msg;
        }

        // ===========================================双横线内编码===================================================
        // 按协议版本1.0解析
//        if (protocolVersion == ProtocolCommand.PROTOCOL_VERSION) {

            // 这里代码的约定
            // 处理业务过程遇到任何错误、异常、不符合逻辑等等情况，一律返回EXCEPTION_CODE_ERROR
            // 处理业务过程完全按照正常逻辑走，返回EXCEPTION_CODE_OK

            switch (cmd) {
            case ProtocolCommand.CMD_REGISTER:
                if (errorCode == ProtocolCommand.CMD_ERROR_NONE) { // 注册成功
                    resultCode = handleRecRegister(context, jsonStr);
                } else if (errorCode == ProtocolCommand.CMD_ACCOUNT) { // 账号已经存在
                    resultCode = handleRecRegister2(dataForClient);
                }
                break;
                
            case ProtocolCommand.CMD_LOGIN: // 处理返回 -登录
                resultCode = handleRecLogin(context, jsonStr, cmds, reCmd);
                break;
                
            case ProtocolCommand.CMD_SET_MY_USER_INFO: //处理返回 -设置个人资料
                if (errorCode == ProtocolCommand.CMD_ERROR_NONE) {
                    resultCode = ERROR_CODE_OK;
                }
                break;
                
            case ProtocolCommand.CMD_QUERY_AROUND_USERS_28_SIZE: //处理返回-查找周边用户
                resultCode = handleRecQueryAroundUsers(context, jsonStr);
                break;
                
            case ProtocolCommand.CMD_QUERY_USER_INFO: //处理返回 -查询用户信息
                resultCode = handleRecQueryUserInfo(context, jsonStr);
                break;
                
            case ProtocolCommand.CMD_QUERY_MY_USER_LIST: //处理返回 - 查询黑名单，共享列表，关注列表
                resultCode = handleRecQueryMyUserInfo(context, jsonStr, reCmd);
                break;
                
            case ProtocolCommand.CMD_CHAT_MSG_NOTIFICATION:
                resultCode = handleRecChatMsg(context, jsonStr, reCmd, dataForClient);
                break;
                
            case ProtocolCommand.CMD_SYSTEM_MSG_NOTIFICATION:
                resultCode = handleRecSystemMsg(context, jsonStr, reCmd, dataForClient);
                break;
                
            case ProtocolCommand.CMD_QUERY_ALBUM: //处理返回 - 查询照片
                resultCode = handleRecQueryAlbum(context, jsonStr, reCmd, dataForClient);
                break;
                
            case ProtocolCommand.CMD_ADD_TO_ALBUM: //处理返回 - 增添照片
                if (errorCode == ProtocolCommand.CMD_ERROR_NONE) {
                    resultCode = ERROR_CODE_OK;
                }
                break;
                
            case ProtocolCommand.CMD_SEND_CHAT_MSG: //聊天消息状态
                resultCode = handleRecChatMsgState(context, jsonStr, reCmd, dataForClient);
                break;
                
            default:
                resultCode = ERROR_CODE_ERROR;
                LogUtil.e(TAG, "服务端发来一个不存在的command: " + cmd);
            }

//        }
        // ===============================================================================================================

        msg.arg1 = resultCode;
        return msg;
    }

    private static int handleRecChatMsgState(Context context, String jsonStr, RECmd reCmd, Bundle dataForClient) {
        
        
        
        
        return 0;
    }

    private static int handleRecChatMsg(Context context, String jsonStr, RECmd reCmd, Bundle dataForClient) {
        if(!CommonUtil.isEmpty(jsonStr)){
            try {
                JSONObject jsonObject = new JSONObject(jsonStr);
                jsonObject = jsonObject.getJSONObject("chat_msg");
                
                int msgType = jsonObject.getInt("chat_msg_type");
                long sendUid = jsonObject.getLong("send_uid");
                long recUid = jsonObject.getLong("recv_uid");
                long sendTime = jsonObject.getInt("send_time");
                long chatMsgId = jsonObject.getInt("chat_msg_id");
                String msgContent = jsonObject.optString("chat_msg_content", "");
                JSONObject locJO = jsonObject.optJSONObject("location");
                
                ChatInfo chatInfo = new ChatInfo();
                chatInfo.chatContent = msgContent;
                chatInfo.chatMarkId = chatMsgId;
                chatInfo.friendUid = sendUid;
                if(null != locJO){
                    String lon = locJO.optString("longitude", "0");
                    String lat = locJO.optString("latitude", "0");
                    chatInfo.lonAndLat = lon + "," + lat;
                }
                chatInfo.msgType = msgType;
                final long myUid = GeePrefrence.getMyUid(context);
                if(myUid != recUid){
                    LogUtil.e(TAG, "服务端出现重大错误，消息发错人了");
                    return ERROR_CODE_ERROR;
                }
                chatInfo.recUid = recUid;
                chatInfo.sendDate = sendTime;
                chatInfo.sendUid = sendUid;
                
                if(msgType == ChatInfo.MSG_TYPE_VOICE){
//                    chatInfo.voiceFileId = ;
//                    chatInfo.voicePlayState = ;
                    //下载好了才插进数据库，通知界面
                    return ERROR_CODE_ERROR;
                }else{
                    chatInfo.saveChatInfo(context);
                }
                return ERROR_CODE_OK;
            } catch (JSONException e) {
                LogUtil.e(TAG, "接收聊天信息有异常", e);
            }
        }
        return ERROR_CODE_ERROR;
    }

    private static int handleRecSystemMsg(Context context, String jsonStr, RECmd reCmd, Bundle dataForClient) {
        if(!CommonUtil.isEmpty(jsonStr)){
            try {
                JSONObject jsonObject = new JSONObject(jsonStr);
                jsonObject = jsonObject.getJSONObject("system_msg");
                
                int systemMsgType = jsonObject.getInt("system_msg_type");
                long sendTime = jsonObject.getLong("send_time");
                long timeOut = jsonObject.getLong("timeout");
                long systemMsgId = jsonObject.getLong("system_msg_id");
                JSONArray jsonArray = jsonObject.getJSONArray("chat_msg_content");
                
                switch (systemMsgType) {
                
                case 10002:
                    LogUtil.e(TAG, "=======================财富通知===========================");
                    LogUtil.e(TAG, jsonStr);
                    LogUtil.e(TAG, "==================================================");
                    LogUtil.e(TAG, "==================================================");
                    LogUtil.e(TAG, "==================================================");
                    LogUtil.e(TAG, "==================================================");
                    LogUtil.e(TAG, "==================================================");
                    LogUtil.e(TAG, "==================================================");
                    LogUtil.e(TAG, "==================================================");
                    LogUtil.e(TAG, "==================================================");
                    LogUtil.e(TAG, "==================================================");
                    LogUtil.e(TAG, "==================================================");
                    LogUtil.e(TAG, "===========================");
                    break;
                    
                case 20004:
                    LogUtil.e(TAG, "=======================偶遇===========================");
                    LogUtil.e(TAG, jsonStr);
                    LogUtil.e(TAG, "==================================================");
                    LogUtil.e(TAG, "==================================================");
                    LogUtil.e(TAG, "==================================================");
                    LogUtil.e(TAG, "==================================================");
                    LogUtil.e(TAG, "==================================================");
                    LogUtil.e(TAG, "==================================================");
                    LogUtil.e(TAG, "==================================================");
                    LogUtil.e(TAG, "==================================================");
                    LogUtil.e(TAG, "==================================================");
                    LogUtil.e(TAG, "==================================================");
                    LogUtil.e(TAG, "===========================");
                    break;

                case 20005:
                    LogUtil.e(TAG, "=======================收到送花===========================");
                    LogUtil.e(TAG, jsonStr);
                    LogUtil.e(TAG, "==================================================");
                    LogUtil.e(TAG, "==================================================");
                    LogUtil.e(TAG, "==================================================");
                    LogUtil.e(TAG, "==================================================");
                    LogUtil.e(TAG, "==================================================");
                    LogUtil.e(TAG, "==================================================");
                    LogUtil.e(TAG, "==================================================");
                    LogUtil.e(TAG, "==================================================");
                    LogUtil.e(TAG, "==================================================");
                    LogUtil.e(TAG, "==================================================");
                    LogUtil.e(TAG, "===========================");
                    break;
                    
                case 30001:
                    LogUtil.e(TAG, "=======================系统消息推送===========================");
                    LogUtil.e(TAG, jsonStr);
                    LogUtil.e(TAG, "==================================================");
                    LogUtil.e(TAG, "==================================================");
                    LogUtil.e(TAG, "==================================================");
                    LogUtil.e(TAG, "==================================================");
                    LogUtil.e(TAG, "==================================================");
                    LogUtil.e(TAG, "==================================================");
                    LogUtil.e(TAG, "==================================================");
                    LogUtil.e(TAG, "==================================================");
                    LogUtil.e(TAG, "==================================================");
                    LogUtil.e(TAG, "==================================================");
                    LogUtil.e(TAG, "===========================");
                    break;
                    
                default: LogUtil.e(TAG, "有系统消息没有处理，type:" + systemMsgType);
                    break;
                }
                
                
                
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return ERROR_CODE_ERROR;
    }

    private static int handleRecQueryAlbum(Context context, String jsonStr, RECmd reCmd, Bundle bundle) {
        if(!CommonUtil.isEmpty(jsonStr)){
            try {
                JSONObject sendJsonObject = new JSONObject(reCmd.jsonStr);
                long uid = sendJsonObject.getLong("uid");
                int photoType = sendJsonObject.getInt("type");
                bundle.putInt("photoType", photoType);
                
                JSONObject jsonObject = new JSONObject(jsonStr);
                JSONArray jsonArray = jsonObject.optJSONArray("photo_ids");
                if(null != jsonArray && jsonArray.length() > 0){
                    String jsonArrayStr = jsonArray.toString();
                    jsonArrayStr = jsonArrayStr.trim();
                    jsonArrayStr = jsonArrayStr.substring(1, jsonArrayStr.length()-1);
                    jsonArrayStr = jsonArrayStr.replace("\"", "");
                    
                    ContentValues cv = new ContentValues();
                    cv.put(BaseUserInfo.EXTRA_UID, uid);
                    if(photoType == Integer.valueOf(DataKey.S_VALUE_USER_PHOTO_TYPE_PUBLIC)){
                        cv.put(BaseUserInfo.EXTRA_PUBLIC_PHOTO_IDS, jsonArrayStr);
                    }else if(photoType == Integer.valueOf(DataKey.S_VALUE_USER_PHOTO_TYPE_PRIVATE)){
                        cv.put(BaseUserInfo.EXTRA_PRIVATE_PHOTO_IDS, jsonArrayStr);
                    }else{
                        LogUtil.e(TAG, "unknow photoType: " + photoType);
                    }
                    BaseUserInfo.saveOrUpdateUserInfo(context, cv);
                }
                
                return ERROR_CODE_OK;
            } catch (JSONException e) {
                LogUtil.e(TAG, "处理查询相册有异常", e);
            }
        }
        return ERROR_CODE_ERROR;
    }

    private static int handleRecQueryMyUserInfo(Context context, String jsonStr, RECmd recCmd) {
        if(null != recCmd && !CommonUtil.isEmpty(jsonStr)){
            long time = 0l;
            String userList = "";
            String userActionTimes = "";
            try {
                JSONObject jsonObject = new JSONObject(jsonStr);
                time = jsonObject.optLong("last_modify_time");
                JSONArray jsonArrayUserList = jsonObject.optJSONArray("user_list");
                JSONArray jsonArrayBuildTimeList = jsonObject.optJSONArray("build_time_list");
                if(null != jsonArrayUserList && jsonArrayUserList.length() > 0){
                    userList = jsonArrayUserList.toString().replace("\"", "");
                    userList = userList.substring(1, userList.length() - 1);
                }
                if(null != jsonArrayUserList && jsonArrayUserList.length() > 0){
                    userActionTimes = jsonArrayBuildTimeList.toString().replace("\"", "");
                    userActionTimes = userActionTimes.substring(1, userActionTimes.length() - 1);
                }
            } catch (JSONException e) {
                LogUtil.e(TAG, "处理拉取我的用户列表异常", e);
            }
            ContentValues cv = new ContentValues();
            cv.put(BaseUserInfo.EXTRA_UID, GeePrefrence.getMyUid(context));
            if(recCmd.cmdType == RECmd.CMD_TYPE_MY_ATTENTION_LIST){
                LogUtil.i(TAG, "处理拉取关注列表");
                cv.put(BaseUserInfo.EXTRA_ATTENTION_MODIFY_TIME, time);
                GeePrefrence.setAttentionList(context, userList);
                GeePrefrence.setAttentionListTimes(context, userActionTimes);
            }else if(recCmd.cmdType == RECmd.CMD_TYPE_MY_BLACK_LIST){
                LogUtil.i(TAG, "处理拉黑名单注列表");
                cv.put(BaseUserInfo.EXTRA_BLACK_MODIFY_TIME, time);
                GeePrefrence.setBlackList(context, userList);
                GeePrefrence.setBlackListTimes(context, userActionTimes);
            }else if(recCmd.cmdType == RECmd.CMD_TYPE_MY_SHARE_LIST){
                LogUtil.i(TAG, "处理拉共享列表");
                cv.put(BaseUserInfo.EXTRA_SHARE_MODIFY_TIME, time);
                GeePrefrence.setShareList(context, userList);
                GeePrefrence.setShareListTimes(context, userActionTimes);
            }
            BaseUserInfo.updateUserInfo(context, cv);
            return ERROR_CODE_OK;
        }else{
            LogUtil.e(TAG, "处理返回查询我的用户列表有异常，发送recmd is null   或者  jsonStr is null");
            return ERROR_CODE_ERROR;
        }
    }

    private static int handleRecQueryUserInfo(Context context, String jsonStr) {
        try {
            ContentValues cv = new ContentValues();
            JSONObject jsonObject = new JSONObject(jsonStr);
            jsonObject = jsonObject.getJSONObject("user_info");
            
            //=========基本信息========
            JSONObject baseUserInfoObject = jsonObject.getJSONObject("user_base_info");
            
            long uid = baseUserInfoObject.getLong("uid");
            long lastInfoModifyTime = baseUserInfoObject.optLong("last_modify_time", 0);
            int isOnline = baseUserInfoObject.getInt("is_online");
            String nickName = baseUserInfoObject.optString("nick_name", "");
            int popValue = baseUserInfoObject.optInt("pop_value", 0);
            String mainPhotoId = baseUserInfoObject.optString("main_photo_id", "");
            long lastOnlineTime = baseUserInfoObject.optLong("last_online_time", 0);
            int isGuest = baseUserInfoObject.getInt("is_guest");
            int userRole = baseUserInfoObject.getInt("user_role");
            JSONObject lonAndLatJO = baseUserInfoObject.getJSONObject("latest_location");
            String lon = lonAndLatJO.optString("longitude", "0");
            String lat = lonAndLatJO.optString("latitude", "0");
            String lonAndLat = lon + "," + lat;
            
            cv.put(BaseUserInfo.EXTRA_UID, uid);
            cv.put(BaseUserInfo.EXTRA_IS_ONLINE, isOnline);
            cv.put(BaseUserInfo.EXTRA_NICK_NAME, nickName);
            cv.put(BaseUserInfo.EXTRA_POP_VALUE, popValue);
            cv.put(BaseUserInfo.EXTRA_LAST_MODIFY_TIME, lastInfoModifyTime);
            cv.put(BaseUserInfo.EXTRA_MAIN_PHOTO_ID, mainPhotoId);
            cv.put(BaseUserInfo.EXTRA_LAST_ONLINE_TIME, lastOnlineTime);
            cv.put(BaseUserInfo.EXTRA_IS_GUEST, isGuest);
            cv.put(BaseUserInfo.EXTRA_ROLE, userRole);
            cv.put(BaseUserInfo.EXTRA_LON_AND_LAT, lonAndLat);
            cv.put(BaseUserInfo.EXTRA_DISTANCE, AndroidUtil.getDistanceWithMe(context, lonAndLat));
            
            //==========扩展信息=========
            JSONObject extUserInfoObject = jsonObject.getJSONObject("user_ext_info");
            
            cv.put(BaseUserInfo.EXTRA_LAST_ALBUM_MODIFY_TIME, extUserInfoObject.optLong("album_modify_time", 0));
            cv.put(BaseUserInfo.EXTRA_HEIGHT, extUserInfoObject.optInt("user_height", 0));
            int weight = extUserInfoObject.optInt("user_weight", 0);
            if(weight > 0){
                weight = (int)(((float)weight) * 0.1f);
            }
            cv.put(BaseUserInfo.EXTRA_WEIGHT, weight);
            cv.put(BaseUserInfo.EXTRA_SIGN, extUserInfoObject.optString("user_sign", ""));
//            cv.put(BaseUserInfo.EXTRA_ROLE, extUserInfoObject.getInt("user_role"));
            cv.put(BaseUserInfo.EXTRA_AGE, extUserInfoObject.optInt("user_age", 0));
            
            BaseUserInfo.updateUserInfo(context, cv);
            
            return ERROR_CODE_OK;
            
        } catch (JSONException e) {
            LogUtil.e(TAG, "处理请求用户信息应答JSON异常", e);
            return ERROR_CODE_ERROR;
        }
        
    }

    private static int handleRecQueryAroundUsers(Context context, String jsonStr) {
        if (CommonUtil.isEmpty(jsonStr)) {
            LogUtil.e(TAG, "拉取周边用户返回jsonStr为null");
            return ERROR_CODE_ERROR;
        }
        try {
            JSONObject jo = new JSONObject(jsonStr);
            JSONArray jsonArray = jo.getJSONArray("users_base_info");
            int size = jsonArray.length();
            LogUtil.i(TAG, "请求周边返回" + size + "个用户");
            if(size > 0){
                JSONObject userInfoObject;
                ContentValues[] cvs = new ContentValues[size];
                ContentValues cv;
                for(int i=0; i<size; i++){
                    userInfoObject = jsonArray.getJSONObject(i);
                    userInfoObject = userInfoObject.getJSONObject("user_base_info");
                    
                    long uid = userInfoObject.getLong("uid");
                    String nickName = userInfoObject.getString("nick_name");
                    String mainPhotoId = userInfoObject.getString("main_photo_id");
                    int isOnline = userInfoObject.getInt("is_online");
                    int popValue = userInfoObject.getInt("pop_value");
                    long lastOnlineTime = userInfoObject.getLong("last_online_time");
                    long lastModifyTime = userInfoObject.getLong("last_modify_time");
                    int userRole = userInfoObject.getInt("user_role");
                    JSONObject locObject = userInfoObject.getJSONObject("latest_location");
                    String friendLonAndLat = locObject.getString("longitude") + "," + locObject.getString("latitude");
                    
                    cv = new ContentValues();
                    cv.put(BaseUserInfo.EXTRA_UID, uid);
                    cv.put(BaseUserInfo.EXTRA_NICK_NAME, nickName);
                    cv.put(BaseUserInfo.EXTRA_MAIN_PHOTO_ID, mainPhotoId);
                    cv.put(BaseUserInfo.EXTRA_IS_ONLINE, isOnline);
                    cv.put(BaseUserInfo.EXTRA_POP_VALUE, popValue);
                    cv.put(BaseUserInfo.EXTRA_LAST_ONLINE_TIME, lastOnlineTime);
                    cv.put(BaseUserInfo.EXTRA_LAST_MODIFY_TIME, lastModifyTime);
                    cv.put(BaseUserInfo.EXTRA_ROLE, userRole);
                    cv.put(BaseUserInfo.EXTRA_LON_AND_LAT, friendLonAndLat);
                    cv.put(BaseUserInfo.EXTRA_DISTANCE, AndroidUtil.getDistanceWithMe(context, friendLonAndLat));
                    
                    cvs[i] = cv;
                }
                BaseUserInfo.saveOrUpdateBatch(context, cvs);
                LogUtil.i(TAG, size + "个周边用户插入数据库完毕");
            }
            return ERROR_CODE_OK;
        } catch (JSONException e) {
            LogUtil.e(TAG, "处理拉取周边用户应答JSON异常", e);
            return ERROR_CODE_ERROR;
        }
    }

    /**
     * 
     * @param jsonStr
     * @return
     */
    private static int handleRecLogin(Context context, String jsonStr, ConcurrentHashMap<Integer, RECmd> cmds, RECmd recmdParam) {
        if (CommonUtil.isEmpty(jsonStr)) {
            LogUtil.e(TAG, "login返回jsonStr为null");
            return ERROR_CODE_ERROR;
        }
        
        try {
            JSONObject jsonObject = new JSONObject(jsonStr);

            long sid = jsonObject.getLong("sid");
            //改变session之前，需要把队列里的session都先改变
            if(cmds.size() > 0){
                Set<Integer> keys = cmds.keySet();
                for(Integer key : keys){
                    RECmd recmd = cmds.get(key);
                    recmd.changeSession(sid);
                }
            }
            GeePrefrence.setMySessionId(context, sid);
            
            long serverTime = jsonObject.optLong("server_time", 0);
            GeePrefrence.setLoginServerTime(context, serverTime);

            // ============================扩展信息user_ext_info==================================
            JSONObject userInfo = jsonObject.getJSONObject("user_ext_info");
            ContentValues cv = new ContentValues();
            cv.put(BaseUserInfo.EXTRA_LAST_ALBUM_MODIFY_TIME, userInfo.optLong("album_modify_time", 0));
            cv.put(BaseUserInfo.EXTRA_HEIGHT, userInfo.optInt("user_height", 0));
            cv.put(BaseUserInfo.EXTRA_WEIGHT, userInfo.optInt("user_weight", 0));
            cv.put(BaseUserInfo.EXTRA_SIGN, userInfo.optString("user_sign", ""));
            cv.put(BaseUserInfo.EXTRA_ROLE, userInfo.optInt("user_role", BaseUserInfo.ROLE_NONE));
            cv.put(BaseUserInfo.EXTRA_AGE, userInfo.optInt("user_age", 0));

            // ============================我的账户信息信息my_account_info==================================
            userInfo = jsonObject.getJSONObject("my_account_info");
            JSONArray visitTimes = userInfo.getJSONArray("build_time_list");
            int length = visitTimes.length();
            StringBuilder sb = new StringBuilder();
            String temp;
            for (int i = 0; i < length; i++) {
                temp = null;
                temp = visitTimes.getString(i);
                if (!CommonUtil.isEmpty(temp)) {
                    sb.append(temp);
                    sb.append(',');
                }
            }
            if (sb.length() > 0) {
                temp = sb.deleteCharAt(sb.length() - 1).toString();
                cv.put(BaseUserInfo.EXTRA_VISIT_TIMES, temp);
            }
            JSONArray visitorIds = userInfo.getJSONArray("my_visitor_list");
            length = visitorIds.length();
            sb = new StringBuilder();
            for (int i = 0; i < length; i++) {
                temp = null;
                temp = visitorIds.getString(i);
                if (!CommonUtil.isEmpty(temp)) {
                    sb.append(temp);
                    sb.append(',');
                }
            }
            if (sb.length() > 0) {
                temp = sb.deleteCharAt(sb.length() - 1).toString();
                cv.put(BaseUserInfo.EXTRA_VISITOR_IDS, temp);
            }
            
            int money = userInfo.optInt("money", 0);
            cv.put(BaseUserInfo.EXTRA_MONEY, money);
            String account = userInfo.getString("account_name");
            cv.put(BaseUserInfo.EXTRA_ACCOUNT_NAME, account);
            
            // ================================我的私密信息my_private_info==========================================
            userInfo = jsonObject.getJSONObject("my_private_info");
            long attentionModifyTime = userInfo.optLong("interest_modify_time", 0);
            long privatePhotoModifyTime = userInfo.optLong("private_album_modify_time", 0);
            long sharePhotoModifyTime = userInfo.optLong("private_album_modify_time", 0);
            int myFansCount = userInfo.optInt("my_fans_count", 0);
            long blackModifyTime = userInfo.optLong("black_modify_time", 0);
            
            cv.put(BaseUserInfo.EXTRA_ATTENTION_MODIFY_TIME, attentionModifyTime);
            cv.put(BaseUserInfo.EXTRA_PRIVATE_ALBUM_MODIFY_TIME, privatePhotoModifyTime);
            cv.put(BaseUserInfo.EXTRA_SHARE_MODIFY_TIME, sharePhotoModifyTime);
            cv.put(BaseUserInfo.EXTRA_MY_FANS_COUNT, myFansCount);
            cv.put(BaseUserInfo.EXTRA_BLACK_MODIFY_TIME, blackModifyTime);

            // =============================我的基础信息user_base_info============================
            userInfo = jsonObject.getJSONObject("user_base_info");
            
            int isOnline = userInfo.optInt("is_online", BaseUserInfo.USER_ONLINE);
            String nickName = userInfo.optString("nick_name", "");
            int popValue = userInfo.optInt("pop_value", 0);
            long lastInfoModifyTime = userInfo.optLong("last_modify_time", 0);
            String mainPhotoId = userInfo.optString("main_photo_id", "");
            long lastOnlineTime = userInfo.optLong("last_online_time", 0);
            int isGuest = userInfo.getInt("is_guest");
            JSONObject lonAndLatJO = userInfo.getJSONObject("latest_location");
            String lon = lonAndLatJO.optString("longitude", "0");
            String lat = lonAndLatJO.optString("latitude", "0");
            String lonAndLat = lon + "," + lat;
            
            cv.put(BaseUserInfo.EXTRA_IS_ONLINE, isOnline);
            cv.put(BaseUserInfo.EXTRA_NICK_NAME, nickName);
            cv.put(BaseUserInfo.EXTRA_POP_VALUE, popValue);
            cv.put(BaseUserInfo.EXTRA_LAST_MODIFY_TIME, lastInfoModifyTime);
            cv.put(BaseUserInfo.EXTRA_MAIN_PHOTO_ID, mainPhotoId);
            cv.put(BaseUserInfo.EXTRA_LAST_ONLINE_TIME, lastOnlineTime);
            cv.put(BaseUserInfo.EXTRA_IS_GUEST, isGuest);
            cv.put(BaseUserInfo.EXTRA_LON_AND_LAT, lonAndLat);
            
            long uid = userInfo.getLong("uid");
            GeePrefrence.setMyUid(context, uid);
            cv.put(BaseUserInfo.EXTRA_UID, uid);
            
            GeePrefrence.setMyMainPhotoId(context, mainPhotoId);
            
            // ===========================================================
            
            cv.put(BaseUserInfo.EXTRA_DISTANCE, "0");
//            cv.put(BaseUserInfo.EXTRA_PUBLIC_PHOTO_IDS, "");
//            cv.put(BaseUserInfo.EXTRA_PRIVATE_PHOTO_IDS, "");
            
            
            RECmd heartBeat = new RECmd(context);
            heartBeat.initHeartBeatData();
            cmds.put(heartBeat.sequenceID, heartBeat);
            LogUtil.v(TAG, "放进心跳包");
            
            RECmd reportLoc = new RECmd(context);
            reportLoc.initReportLocData(context);
            cmds.put(reportLoc.sequenceID, reportLoc);
            LogUtil.v(TAG, "放进上报loc包");
            
            if(recmdParam.cmdType != RECmd.CMD_TYPE_RELOGIN){
                
                RECmd getBlackListRecmd = new RECmd(context);
                getBlackListRecmd.initMyUserData(context, RECmd.CMD_TYPE_MY_BLACK_LIST);
                cmds.put(getBlackListRecmd.sequenceID, getBlackListRecmd);
                
                RECmd getShareListRecmd = new RECmd(context);
                getShareListRecmd.initMyUserData(context, RECmd.CMD_TYPE_MY_SHARE_LIST);
                cmds.put(getShareListRecmd.sequenceID, getShareListRecmd);
                
//                RECmd getAttentionListRecmd = new RECmd(context);
//                getAttentionListRecmd.initMyUserData(context, RECmd.CMD_TYPE_MY_ATTENTION_LIST);
//                cmds.put(getAttentionListRecmd.sequenceID, getAttentionListRecmd);
                
            }
            
            BaseUserInfo.saveOrUpdateUserInfo(context, cv);
            
            return ERROR_CODE_OK;
        } catch (Exception e) {
            LogUtil.e(TAG, "处理登录应答JSON异常", e);
        }
        return ERROR_CODE_ERROR;
    }

    /**
     * 注册处理
     * 
     * @param jsonStr
     * @return
     */
    private static int handleRecRegister(Context context, String jsonStr) {
        if (!CommonUtil.isEmpty(jsonStr)) {
            try {
                long uid = 0;
                JSONObject jsonObject = new JSONObject(jsonStr);
                uid = jsonObject.optLong("uid");
                if (uid > 0) {
                    GeePrefrence.setMyUid(context, uid);
                    LogUtil.i(TAG, "注册成功, uid:" + uid);
                    return ERROR_CODE_OK;
                } else {
                    LogUtil.e(TAG, "严重问题，从服务端获取的uid不在约定范围内");
                }
            } catch (JSONException e) {
                LogUtil.e(TAG, "处理注册应答JSON异常", e);
            }
        } else {
            LogUtil.e(TAG, "register返回jsonStr为null");
        }
        return ERROR_CODE_ERROR;
    }

    /**
     * 处理账号已存在情况
     * 
     * @param dataForClient
     * @return
     */
    private static int handleRecRegister2(Bundle dataForClient) {
        // 告诉activity账号已经存在
        dataForClient.putInt(DataKey.R_KEY_REGISTER_ACCOUNT_EXIST, DataKey.R_VALUE_REGISTER_ACCOUNT_EXIST);
        return ERROR_CODE_OK;
    }

}
